'use strict';

const Controller = require('egg').Controller;

class WordController extends Controller {
    //创建
    async create() {
        let {ctx,service} = this;
        let {title,con,s_id} = ctx.request.body;
        let time = new Date();
        let {uid} = ctx.info;
        //1.容错处理
        if(title && con && s_id){
            //2.排重
            let selectWord = await service.word.selectWord(title);
            if(selectWord.length){
                //3.此文档已存在
                ctx.body = {
                    code:3,
                    msg:'次文档已存在'
                }
            }else{
                //4.不存在
                try{
                    await service.word.create(title,con,uid,s_id,time);
                    ctx.body = {
                        code:1,
                        msg:'创建成功'
                    }
                }catch(e){
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //更新
    async update(){
        let {ctx,service} = this;
        let {title,con} = ctx.request.body;
        let time = new Date();
        let {id} = ctx.params;
        //1.容错处理
        if(title && con && id){
            try{
                await service.word.update(title,con,id,time);
                ctx.body = {
                    code:1,
                    msg:'更新成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //查询
    async index(){
        let {ctx,service} = this;
        let {uid} = ctx.info;
        let wordlist = await service.word.index(uid);
        ctx.body = {
            code:1,
            data:wordlist
        }
    }
    //删除
    async destroy(){
        let {ctx,service} = this;
        let {id} = ctx.params;
        //容错处理
        try{
            await service.word.delete(id);
            ctx.body = {
                code:1,
                msg:'删除成功'
            }
        }catch(e){
            ctx.body = {
                code:2,
                msg:e
            } 
        }
    }
    //查询此知识库的详情
    async show(){
        let {ctx,service} = this;
        let {id} = ctx.params;
        if(id){
            let wordList = await service.word.show(id);
            ctx.body = {
                code:1,
                data:wordList
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
}

module.exports = WordController;

/**
 * get  ctx.query
 * 
 * post ctx.request.body
 * 
 * 动态路由 /api/word/4  ctx.params
 * 
 * */ 
